import 'dart:math';
import 'package:flutter/material.dart';
import 'package:pacsun/view/create/createBecomeCreator.dart';
// -------------------------------------------------------------------//
import 'package:pacsun/model/userModel.dart' show UserModel;
import 'package:pacsun/model/sysUserTagModel.dart' show YouAreTagModel;
import 'package:pacsun/model/userLoginModel.dart' show UserLoginModel;
// -------------------------------------------------------------------//
//import 'package:pacsun/services/uploadService.dart' show UploadService;
import 'package:pacsun/services/userService.dart' show UserService;

// -------------------------------------------------------------------//
import 'package:pacsun/utils/notifyMsg.dart' show notifyMsg;

class UserProvider with ChangeNotifier {
  UserModel? _currentUser;
  bool _isLoading = false;
  bool _isLogin = false;
  String? _error;

  UserModel? get currentUser => _currentUser;
  bool get isLoading => _isLoading;
  bool get isLogin => _isLogin;
  String? get error => _error;
  bool get isCreate => _currentUser?.userType == 1 ? true : false;

  /// * Fetched user data in not completed here.
  /// * Refer to getUserInfo for fetching complete user info
  Future<void> login(
      String username, String password, BuildContext context) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final loginModel = UserLoginModel(
          userCode: username.trim(), plainUserPwd: password.trim());

      _currentUser = await UserService().login(loginModel);

      _isLogin = true;

      notifyListeners();

      print('=== UserProvider 登录成功 ===');
      //  print('用户信息: $_currentUser');
      print('登录状态: $_isLogin');

      notifyMsg('Login successful, welcome!', context);
    } catch (e) {
      _error = e is String ? e : e.toString();
      notifyMsg(_error!, context);
      throw 'Login Error';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// * Fetching user info
  /// * Overwrite current user data
  Future<void> getUserInfo(int userId, BuildContext context) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      _currentUser = await UserService().getUserInfo(userId);

      notifyListeners();
    } catch (e) {
      _error = e is String ? e : e.toString();
      notifyMsg(_error!, context);
    } finally {
      print('=== UserProvider Fetching User Data Successfully ===');
      print('${_currentUser}');
      _isLoading = false;
      notifyListeners();
    }
  }

  /// * Using for update user info
  /// * Should receiving {}, e.g.:
  /// * {'id':  001}
  ///
  Future<void> updateUserInfo(UserModel updatedUser,
      {BuildContext? context}) async {
    if (_currentUser == null) {
      _error = 'No user is currently logged in';
      if (context != null) notifyMsg(_error!, context);
      return;
    }

    _isLoading = true;
    notifyListeners();

    try {
      // Create updated user using copyWith, passing all fields from updatedUser
      _currentUser = _currentUser!.copyWith(
        id: updatedUser.id,
        aid: updatedUser.aid,
        nickName: updatedUser.nickName,
        imageUrl: updatedUser.imageUrl,
        createTime: updatedUser.createTime,
        updateTime: updatedUser.updateTime,
        fullName: updatedUser.fullName,
        email: updatedUser.email,
        address: updatedUser.address,
        socialAccounts: updatedUser.socialAccounts,
        userType: updatedUser.userType,
        bio: updatedUser.bio,
        taskCountId: updatedUser.taskCountId,
        inviterAid: updatedUser.inviterAid,
        firstName: updatedUser.firstName,
        lastName: updatedUser.lastName,
        password: updatedUser.password,
        confirmPassword: updatedUser.confirmPassword,
        phone: updatedUser.phone,
        birthday: updatedUser.birthday,
        shoppingFor: updatedUser.shoppingFor,
        mediaType: updatedUser.mediaType,
        deleted: updatedUser.deleted,
        status: updatedUser.status,
        createUser: updatedUser.createUser,
        updateUser: updatedUser.updateUser,
        followers: updatedUser.followers,
        youAre: updatedUser.youAre,
        connected: updatedUser.connected,
        openId: updatedUser.openId,
      );

      if (context != null) {
        notifyMsg('User information updated successfully', context);
      }
    } catch (e) {
      _error = e is String ? e : e.toString();
      if (context != null) notifyMsg(_error!, context);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// * Registering Creator
  /// *
  Future<void> registerCreator(
      BuildContext context, Map<String, dynamic> submittedData) async {
    if (_currentUser == null) {
      _error = 'You must be logged in to become a creator';
      notifyMsg(_error!, context);
      return;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final successMessage = await UserService()
          .registerCreator(UserModel.fromJson(submittedData));

      _currentUser = _currentUser!.copyWith(
          fullName: submittedData['fullName'],
          phone: submittedData['phone'],
          birthday: submittedData['birthday'],
          email: submittedData['email'],
          mediaType: submittedData['mediaType'],
          youAre: submittedData['submittedData'],
          openId: submittedData['openId'],
          userType: 1);

      notifyMsg(successMessage.toString(), context);
    } catch (e) {
      _error = e is String ? e : e.toString();
      //  _currentUser = _currentUser!.copyWith(userType: 0);
      notifyMsg(_error!, context);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// * Update tiktok linking status
  /// * please sending into openId
  /// * structure exp.: {'tiktok' : 'openId'}

  Future<void> updateTiktokLinkStatus(
      BuildContext context, String openId) async {
    if (_currentUser == null) {
      _error = 'You must be logged in';
      notifyMsg(_error!, context);
      return;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      // Update the user using copyWith to maintain immutability
      _currentUser = _currentUser!.copyWith(connected: {'tiktok': openId});

      // Optional: You might want to persist this to your backend here
      // await UserService().updateConnectedAccounts(updatedConnected);
    } catch (e) {
      _error = e is String ? e : e.toString();
      if (context != null) notifyMsg(_error!, context);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> updateProfile(
      BuildContext context, Map<String, dynamic> data, int? taskId) async {
    if (_currentUser == null) {
      _error = 'Opps, user information seems missing...';
      notifyMsg(_error!, context);
      return;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      data['id'] = _currentUser!.id;
      data['aid'] = _currentUser!.aid;
      data['mediaType'] = _currentUser!.connected?['tiktok'] != null ? 1 : 0;
      data['openId'] = _currentUser!.connected?['tiktok'] != null
          ? _currentUser!.connected!['tiktok']
          : null;

      final successMessage = await UserService().updateProfile(data, taskId);

      _currentUser = _currentUser!.copyWith(
        nickName: data['nickname'],
        imageUrl: data['imageUrl'],
        birthday: data['dob'],
        bio: data['bio'],
        youAre: data['youAre'],
        connected: {'tiktok': data['tiktok']},
      );

      notifyMsg(successMessage.toString(), context);
    } catch (e) {
      _error = e is String ? e : e.toString();
      notifyMsg(_error!, context);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> updateStoreFront(
      BuildContext context, imageUrl, int? taskId) async {
    if (_currentUser == null) {
      _error = 'Opps, user information seems missing...';
      notifyMsg(_error!, context);
      return;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final Map<String, dynamic> data = {};
      data['id'] = _currentUser!.id;
      data['aid'] = _currentUser!.aid;
      data['imageUrl'] = _currentUser!.imageUrl;
      // data['mediaType'] = _currentUser!.connected?['tiktok'] != null ? 1 : 0;
      // data['openId'] = _currentUser!.connected?['tiktok'] != null
      //     ? _currentUser!.connected!['tiktok']
      //     : null;

      final successMessage = await UserService().updatePutStore(data, taskId);

      // _currentUser = _currentUser!.copyWith(
      //   nickName: data['nickname'],
      //   imageUrl: data['imageUrl'],
      //   birthday: data['dob'],
      //   bio: data['bio'],
      //   youAre: data['youAre'],
      //   connected: {'tiktok': data['tiktok']},
      // );

      notifyMsg(successMessage.toString(), context);
    } catch (e) {
      _error = e is String ? e : e.toString();
      notifyMsg(_error!, context);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

// Add this method for mock login
  void mockLoginForDev(int? userTy) {
    _currentUser = UserModel(
      id: Random().nextInt(10000),
      aid: '1fb725dd24a34d51a4eb6839d1428ee3',
      nickName: 'Developer',
      imageUrl:
          'https://aigcblob.blob.core.windows.net/iss-aigc/File/pacsun_202504192148306697.jpeg',
      userType: userTy ?? 0, // Set as creator for testing
      // Add other required fields
      email: 'dev@example.com',
      fullName: 'Vivian Chen',
      birthday: '05/11/1999',
      youAre: '2,3',
      // Include other minimal required fields
    );
    _isLogin = true;
    notifyListeners();
  }

  void logout() {
    _currentUser = null;
    _isLogin = false;
    notifyListeners();
  }
}
